package com.huan.hystrix.service.impl;

import com.huan.hystrix.entity.Product;
import com.huan.hystrix.service.ProductService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * 基于 HystrixCommand 实现回退
 *
 * @author huan.fu
 * @date 2018/8/8 - 15:26
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

	private static final String PRODUCT_URL = "http://localhost:9099/product/%s";

	@Autowired
	private RestTemplate restTemplate;

	@Override
	@HystrixCommand(
			fallbackMethod = "selectOneFallback",
			groupKey = "products",
			commandKey = "ProductServiceImpl.selectOne(String)",
			threadPoolKey = "product-thread",
			commandProperties = {
					@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
			}
	)
	public Product selectOne(String productId) {
		return restTemplate.getForObject(String.format(PRODUCT_URL, productId), Product.class);
	}

	public Product selectOneFallback(String productId, Throwable throwable) {
		log.error("引起回退的异常.", throwable);
		return Product.builder()
				.productId(productId)
				.productName("服务回退")
				.build();
	}
}
